import PageFilterComponent from '@/components/PageFilter/index.vue';
import { AdminUserApi } from '@/api';
import { AdminUserMapping, MappingTools } from '@/mappings';
import _ from 'lodash';
import { mapGetters } from 'vuex';

export default {
  name: 'AdminUserList',
  components: { PageFilterComponent },
  data() {
    return {
      tableData: {
        page: 1,
        pageSize: 20,
        total: 0,
        list: [],
      },
      filterForm: {
        u_account: '',
        u_name: '',
      },
      adminUserDialog: false,
      selection: {},
      roles: [],
      levelEditDialog: false,
      levelOptions: MappingTools.transferOptions(AdminUserMapping.Level),
    };
  },
  created() {
    this.fetchTableData();
    this.fetchRoles();
  },
  computed: {
    ...mapGetters(['user']),
  },
  methods: {
    async fetchTableData() {
      try {
        const response = await AdminUserApi.page({
          page: this.tableData.page,
          pageSize: this.tableData.pageSize,
          ...this.filterForm,
        });
        this.tableData = response.result;
      } catch (response) {
        this.$message.error('管理员列表查询失败：' + response.msg);
      }
    },
    async fetchRoles() {
      const response = await AdminUserApi.getRoles();
      this.roles = response.result.rolelist;
    },
    showAddDialog(row) {
      this.selection = row;
      this.adminUserDialog = true;
    },
    onPageChanged(page) {
      this.tableData.page = page;
      this.fetchTableData();
    },
    onPageSizeChanged(pageSize) {
      this.tableData.pageSize = pageSize;
      this.fetchTableData();
    },
    onSubmitAdminUser() {
      AdminUserApi.add(this.selection)
        .then(() => {
          this.adminUserDialog = false;
          this.$message.success('操作成功');
          this.fetchTableData();
        })
        .catch((response) => {
          this.$message.error('操作失败：' + response.msg);
        });
    },
    matchTableFieldLabelLevel(row, column, cellValue) {
      return MappingTools.matchLabel(AdminUserMapping.Level, cellValue);
    },
    showLevelEditDialog(row) {
      this.selection = _.clone(row);
      this.levelEditDialog = true;
    },
    onEditLevel() {
      AdminUserApi.updateLevel(this.selection.u_id, this.selection.u_level)
        .then(() => {
          this.levelEditDialog = false;
          this.$message.success('操作成功');
          this.fetchTableData();
        })
        .catch((e) => {
          this.$message.error('操作失败：' + JSON.stringify(e));
        });
    },
    resetPassword(row) {
      this.$confirm(`确定重置账号${row.u_account}(${row.u_name})的密码么？`).then(() => {
        AdminUserApi.resetPassword(row.u_id).then((response) => {
          this.$alert(`新密码为：${response.result.new_password}, 请妥善保管，及时修改`)
        }).catch(() => {

        })
      }).catch(() => {

      })
    }
  },
};
